package cn.studyjams.s1.contest.autohello.service;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import cn.studyjams.s1.contest.autohello.R;
import cn.studyjams.s1.contest.autohello.model.Contact;
import cn.studyjams.s1.contest.autohello.model.Event;
import cn.studyjams.s1.contest.autohello.model.RepeatMode;
import cn.studyjams.s1.contest.autohello.receiver.NotificationReceiver;

public class SystemBootService extends IntentService {

    private final static String TAG = "SystemBootService";

    private String notificationText;
    SharedPreferences sharedPref;

    List<Event> mDataset = new ArrayList<>();

    public SystemBootService() {
        super("SystemBootService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        Log.d(TAG, "SystemBootService");

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {
            FirebaseDatabase.getInstance().getReference()
                    .child("events")
                    .child(user.getUid())
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (dataSnapshot != null) {
                                HashMap<String, Object> dataSnapshotValue = (HashMap<String, Object>) dataSnapshot.getValue();
                                if (dataSnapshotValue != null) {
                                    Set<String> set = dataSnapshotValue.keySet();

                                    for (String eventId : set) {

                                        List<Contact> receivers = new ArrayList<>();
                                        RepeatMode repeatMode;

                                        HashMap<String, Object> eventMap = (HashMap<String, Object>) dataSnapshotValue.get(eventId);

                                        int eventType = Integer.parseInt(eventMap.get("type").toString());

                                        String id = eventMap.get("id").toString();
                                        String content = eventMap.get("content").toString();
                                        String tag = eventMap.get("tag").toString();
                                        String dateTime = eventMap.get("dateTime").toString();
                                        int color = Integer.parseInt(eventMap.get("color").toString());
                                        boolean isActive = Boolean.parseBoolean(eventMap.get("isActive").toString());
                                        boolean isDelete = Boolean.parseBoolean(eventMap.get("isDelete").toString());
                                        long requestCode = Long.parseLong(eventMap.get("requestCode").toString());

                                        ArrayList<Map<String, Object>> contacts = (ArrayList<Map<String, Object>>) eventMap.get("receivers");
                                        for (int i = 0; i < contacts.size(); i++) {
                                            HashMap<String, Object> contactMap = (HashMap<String, Object>) contacts.get(i);
                                            String name = contactMap.get("name").toString();
                                            String phoneNumber = contactMap.get("phoneNumber").toString();
                                            String emailAddress = contactMap.get("emailAddress").toString();
                                            int contactType = Integer.parseInt(contactMap.get("type").toString());

                                            Contact contact = new Contact(name, phoneNumber, emailAddress, contactType);
                                            receivers.add(contact);
                                        }

                                        HashMap<String, Object> repeatModeMap = (HashMap<String, Object>) eventMap.get("repeatMode");
                                        int repeatType = Integer.parseInt(repeatModeMap.get("repeatType").toString());
                                        int howOften = Integer.parseInt(repeatModeMap.get("howOften").toString());
                                        int endCondition = Integer.parseInt(repeatModeMap.get("endCondition").toString());
                                        String endDateTime = repeatModeMap.get("endDateTime").toString();
                                        int endCounts = Integer.parseInt(repeatModeMap.get("endCounts").toString());
                                        String whichWeeks = repeatModeMap.get("whichWeeks").toString();
                                        int sameDayOrSameWeekOfTheMonth = Integer.parseInt(repeatModeMap.get("sameDayOrSameWeekOfTheMonth").toString());

                                        repeatMode = new RepeatMode(
                                                repeatType,
                                                howOften,
                                                endCondition,
                                                endDateTime,
                                                endCounts,
                                                whichWeeks,
                                                sameDayOrSameWeekOfTheMonth
                                        );

                                        Event event = new Event(
                                                id,
                                                content,
                                                receivers,
                                                tag,
                                                dateTime,
                                                repeatMode,
                                                color,
                                                isActive,
                                                eventType,
                                                requestCode,
                                                isDelete
                                        );

                                        if (!isDelete){
                                            mDataset.add(event);
                                        }
                                    } // #END# for (String eventId : set)
                                }
                            }// #END# if (dataSnapshot != null)

                            for (Event event : mDataset) {
                                if (event.getIsActive()) {

                                    AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);

                                    Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
                                    intent.putExtra("event_id", event.getId());

                                    PendingIntent alarmIntent = PendingIntent.getBroadcast(
                                            getApplicationContext(),
                                            (int) event.getRequestCode(),
                                            intent,
                                            PendingIntent.FLAG_UPDATE_CURRENT
                                    );

                                    Calendar calendar = Calendar.getInstance();
                                    SimpleDateFormat sdf = new SimpleDateFormat(
                                            "yyyy-MM-dd HH:mm",
                                            Locale.getDefault()
                                    );
                                    try {
                                        calendar.setTime(sdf.parse(event.getDateTime()));
                                        alarmMgr.set(
                                                AlarmManager.RTC,
                                                calendar.getTimeInMillis(),
                                                alarmIntent
                                        );
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            notificationText = "事件闹铃已恢复";
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                            notificationText = "连接数据库失败，" + databaseError.toString();
                        }
                    });

            NotificationManager notificationManager = (NotificationManager) this.
                    getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_hello)
                    .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                    .setContentTitle("系统启动完成")
                    .setContentText(notificationText)
                    .setAutoCancel(true);

            notificationManager.notify((int) System.currentTimeMillis(), builder.build());
        } else {
            NotificationManager notificationManager = (NotificationManager) this.
                    getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_hello)
                    .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                    .setContentTitle("系统启动完成")
                    .setContentText("帐户未登录，无法恢复事件闹铃。请打开软件重新登录！")
                    .setAutoCancel(true);

            setNotifications(builder, true);
            notificationManager.notify((int) System.currentTimeMillis(), builder.build());
        }

    }

    private void setNotifications(NotificationCompat.Builder builder, boolean isError) {
        if (sharedPref.getBoolean("notifications_new_message", true)) {
            if (sharedPref.getBoolean("notifications_new_message_vibrate", true)) {
                if (isError) {
                    builder.setVibrate(new long[]{0, 500, 500, 500});
                } else {
                    builder.setVibrate(new long[]{0, 500});
                }
            }

            String soundStr = sharedPref.getString(
                    "notifications_new_message_ringtone",
                    "DEFAULT_SOUND"
            );

            Uri soundUri = Uri.parse(soundStr);
            builder.setSound(soundUri);
        }
    }
}
